package com.example.service;

import com.example.entity.RateLimitConfig;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RateLimitConfigService {

    @Resource
    private SessionFactory sessionFactory;

    public void addRateLimitConfig(RateLimitConfig config) {
        try (Session session = sessionFactory.openSession()) {
            session.beginTransaction();
            session.save(config);
            session.getTransaction().commit();
        }
    }

    public RateLimitConfig getRateLimitConfigById(int id) {
        try (Session session = sessionFactory.openSession()) {
            return session.get(RateLimitConfig.class, id);
        }
    }

    public List<RateLimitConfig> getAllRateLimitConfigs() {
        try (Session session = sessionFactory.openSession()) {
            return session.createQuery("from RateLimitConfig", RateLimitConfig.class).list();
        }
    }

    public void updateRateLimitConfig(RateLimitConfig config) {
        try (Session session = sessionFactory.openSession()) {
            session.beginTransaction();
            session.update(config);
            session.getTransaction().commit();
        }
    }

    public void deleteRateLimitConfig(int id) {
        try (Session session = sessionFactory.openSession()) {
            session.beginTransaction();
            RateLimitConfig config = session.get(RateLimitConfig.class, id);
            if (config != null) {
                session.delete(config);
            }
            session.getTransaction().commit();
        }
    }
}
